import React,{Component} from 'react';


import {observer,inject} from "mobx-react";
import {computed} from "mobx";


import {View} from "../component/index";
import {
  FileImageOutlined,
  EditOutlined,
  CloseOutlined,
  PlusOutlined,
  SaveOutlined,
  QuestionCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {Select,
  Input,
  Button,
  Modal,
  Popover,
  Tree,
  Table,
  Cascader,
  Upload,
  Image
} from "antd";
const { Option } = Select;
const {TreeNode} = Tree;
const { Search,TextArea } = Input;



const style={
  formItem:{
    marginBottom:10,
    alignItems:"center"
  }
};


// 链接管理
@inject(["store"])
@observer
class Link extends Component{
  constructor(props){
    super(props);
    this.store = props.store;
    this.link = props.store.storeLink;
    if(!this.treeData.length){this.link.init();}
  }
  
  componentDidMount(){
    this.store.navigation({page:"Link"});
  }
  
  // loading
  @computed get loading(){return this.store.loading;}
  // 高度
  @computed get height(){return this.store.height;}
  @computed get treeWidth(){return this.store.treeWidth;}

  // treeData
  @computed get treeData() {return this.link.treeData.slice();}
  @computed get options(){return this.link.options.slice();}
  // 树形所选节点
  @computed get selectedKeys(){return this.link.selectedKeys.slice();}
  // 分页数据
  @computed get data() {return this.link.paging.data.slice();}
  // 查询
  @computed get where() {return this.link.where;}
  // 分页
  @computed get pagination(){
    return {current:Number(this.link.paging.nowPage),total:Number(this.link.paging.maxNum),pageSize:Number(this.link.paging.num)};
  }
  // 表单数据
  @computed get form(){return this.link.form;}

  
  // 树形
  renderTreeNodes = (data) => {
    return data.map((item) => {
      const title = (
        <Popover 
          placement="right" 
          title={item.tit} 
          content={
            <div>
              <p>id:{item.id}</p>
              <p>upid:{item.upid}</p>
              <p>tit:{item.tit}</p>
              <p>cont:{item.cont}</p>
            </div>
          } 
          trigger="contextMenu">
          <span>{item.tit}</span>
        </Popover>
      );
      if (item.children) {
        return (
          <TreeNode title={title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item} title={title} />;
    });
  }

  render(){
    const columns = [
      {title: "编号",dataIndex: "id",width:"10%"},
      {title: "名称",dataIndex: "tit",width:"15%"},
      {title: "图片",dataIndex: "image",width:"15%",render:text=>{return text?<Image alt="图片" style={{width:40,height:40}} src={text} />:<FileImageOutlined />;}},
      {title: "链接",dataIndex: "url",width:"20%"},
      {
        title:"创建时间",
        dataIndex:"createtime",
        width:" 20%",
        render:(text)=>{
          let tm = new Date(Number(text)*1000);
          return <span>{tm.getFullYear()}-{tm.getMonth()+1}-{tm.getDate()}</span>;
        }
      },
      {
        width:"20%",
        title: "相关操作",
        key: "form",
        render: (text ,record)=> {
          return (
            <div>
              <Button
                onClick={()=>{
                  this.link.set("form-visible",true);
                  this.link.set("form-condition","update");
                  this.link.set("form-title","编辑链接id：".concat(record.id));
                  this.link.set("form-data-id",record.id);
                  this.link.set("form-data-tid",record.tid);
                  this.link.set("form-data-ttit",record.ttit);
                  this.link.set("form-data-tit",record.tit);
                  this.link.set("form-data-cont",record.cont);
                  this.link.set("form-data-url",record.url);
                  this.link.set("form-data-image",record.image);
                  this.link.set("form-data-sid",record.sid);
                  
                  this.link.set("form-data-province",record.province);
                  this.link.set("form-data-city",record.city);
                  this.link.set("form-data-county",record.county);
                }}
                icon={<EditOutlined />} style={{marginRight:10}}
                type="primary"
              >
                编辑
              </Button>
              <Button
                onClick={()=>{
                  Modal.confirm({
                    title: "确认删除",
                    content: "是否真的要删除链接？",
                    onOk:()=>this.link.delete(record.id),
                    onCancel() {},
                  });
                }}
                icon={<CloseOutlined />} style={{marginRight:10}}
                type="danger"
              >
                删除
              </Button>
            </div>
          );
        }
      },
    ];
    const form  = this.form;
    const image = /\.(png|jpg|jpeg|gif)$/.test(form.data.image)?<Image alt="图片" style={{width:25,height:25,marginRight:10}} src={form.data.image} />:null;
    return (
      <View style={{overflow:"hidden",height:this.height-50,width:"100%"}}>
        <div
          style={{
            borderRight:"1px #f6f6f6 solid",
            height:this.height-50,
            width:this.treeWidth,
            overflow:"auto",
            padding:"10px"
          }}
          onMouseDown={e => {
            e.preventDefault()
            // e = e || event
            let { clientX, clientY } = e
            let width = parseFloat(this.treeWidth)
            document.body.onmousemove = (e: any) => {
                // e = e || event
                let newWidth = width + (e.clientX - clientX)
                this.store.set("treeWidth",newWidth);
            }
            document.body.onmouseup = function () {
                document.body.onmousemove = null
            }
          }}
          >
          <Tree
            loadData={this.link.onLoadData}
            selectedKeys={this.selectedKeys}
            treeData={this.treeData}
            onSelect={(keys,info)=>{
              this.link.set("where",{
                field:"tid",
                value:keys,
                condition:"="
              });
              this.link.page(1);
              this.link.click(keys,info);
            }}
            showLine
          >
          </Tree>
        </div>
        <div style={{flex:1,overflow:"hidden",height:this.height-50}}>
          <View 
            style={{
              borderBottom:"1px #eee solid",
              height:50,
              alignItems:"center",
              background:"#f2f2f2"
            }}
            >
            <Select
              defaultValue="id"
              onChange={v=>this.link.set("where-field",v)}
              style={{width:"100px",margin:"0 5px"}}
            >
              <Option value="id">链接编号</Option>
              <Option value="tid">分类编号</Option>
            </Select>
            <Select
              defaultValue="="
              onChange={v=>this.link.set("where-condition",v)}
              style={{width:100,margin:"0 5px"}}
            >
              <Option value="=">等于查询</Option>
              <Option value="like">模糊查询</Option>
            </Select>
            <Search
              placeholder="输入查询内容"
              onSearch={value => this.link.search(value)}
              style={{ width: 250 }}
              value={this.where.value}
              onChange={(e)=>this.link.set("where-value",e.target.value)}
              enterButton
            />
            <Button onClick={()=>this.link.init()}  style={{margin:"0 5px 0 20px"}}>所有链接</Button>
            <Button
              onClick={()=>{
                this.link.set("form-visible",true);
                this.link.set("form-condition","insert");
                this.link.set("form-title","新建链接");
                this.link.set("form-data-tit","");
                this.link.set("form-data-cont","");
                this.link.set("form-data-image","");
                this.link.set("form-data-url","");
              }} 
              icon={<PlusOutlined />} 
              type="primary" 
              style={{margin:"0 5px"}}
            >
              创建链接
            </Button>
          </View>
          <View
            style={{
              width:"100%",
              background:"#fff",
              marginBottom:10,
              felxDirection:"column",
              overflow:"auto",
              height:this.height-50
            }}
            >
            <Table
              style={{width:"100%"}}
              scroll={{y:this.height-180,x:"100%"}}
              loading={this.loading}
              rowKey={record => record.id}
              columns={columns}
              dataSource={this.data}
              pagination={this.pagination}
              onChange={pagination=>this.link.page(pagination.current)}
            />
          </View>
        </div>
        <Modal
          mask={false}
          maskClosable={false}
          visible={form.visible}
          title={form.title}
          onCancel={()=>this.link.set("form-visible",false)}
          footer={[
            <Button key="colse" icon={<CloseOutlined />} onClick={()=>this.link.set("form-visible",false)}>关闭</Button>,
            <Button key="submit" icon={<SaveOutlined />} type="primary" loading={this.loading} onClick={()=>this.link.submit()}>保存</Button>,
          ]}
          >
          <View style={style.formItem}>
            <label>所属分类：</label>
            <div style={{flex:1}}>
              <Cascader
                options={this.options}
                loadData={selectedOptions=>this.link.onLoadOption(selectedOptions)}
                onChange={(value,selectedOptions)=>{
                  const len = value.length-1;
                  this.link.set("form-data-ttit",selectedOptions[len].label);
                  this.link.set("form-data-tid",value[len]);
                }}
                changeOnSelect
              >
                <Input readOnly value={form.data.ttit} />
              </Cascader>
            </div>
          </View>
          <View style={style.formItem}>
            <label>商铺编号：</label>
            <Input style={{flex:1}} value={form.data.sid} onChange={e=>this.link.set("form-data-sid",e.target.value)} />
          </View>
          <View style={style.formItem}>
            <label>链接名称：</label>
            <Input style={{flex:1}} value={form.data.tit} onChange={e=>this.link.set("form-data-tit",e.target.value)} />
          </View>
          {
            <View style={style.formItem}>
              <label>链接地址：</label>
              <Input style={{flex:1}} value={form.data.url} onChange={e=>this.link.set("form-data-url",e.target.value)} />
              <Popover
                title="链接类型"
                content={
                  <div>
                    <p>链接地址- http(s)://test.com</p>
                  </div>
                }>
                <Button size="small" style={{marginLeft:5}} type="primary" shape="circle" icon={<QuestionCircleOutlined />} />
              </Popover>
            </View>
          }
          

          <View style={style.formItem}>
            <label>链接图片：</label>
            <View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
              <Input style={{flex:1,marginRight:10}} value={form.data.image} onChange={e=>this.link.set("form-data-image",e.target.value)} />
              {image}
              <Upload
                withCredentials
                showUploadList={false}
                name="image"
                action={this.store.url.concat("?act=admin-upload&tp=image")}
                onChange={info=>this.link.uploadChange(info,"image")}
                >
                <Button size="small" loading={this.loading} type="primary" icon={<UploadOutlined />} />
              </Upload>
            </View>
          </View>
          <View style={style.formItem}>
            <label>链接备注：</label>
            <TextArea style={{flex:1}} value={form.data.cont} onChange={e=>this.link.set("form-data-cont",e.target.value)} />
          </View>
        </Modal>
      </View>
    );
  }
}

export default Link;